import '@/assets/css/index.less';
import ArticlePreview from '@/components/articlePreview';
import ImgUpload from '@/components/ImgUpload';
import IpListModal from '@/components/ipListModal/ipListModal';
import TreeSide from '@/components/TreeSide';
import MyEditor from '@/components/WangEditor';
import MyTextEditor from '@/components/WangEditorText';
import { getCategoryList } from '@/services/category';
import { getGroupList } from '@/services/groupManage';
import {cacheTopic, insertTopic, topicSelectOne, updateTopic} from '@/services/topic';
import {CheckOutlined, EyeOutlined, UndoOutlined, UploadOutlined} from '@ant-design/icons';
import ProForm, { ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import {HOMEPAGE_URL} from "../../../../proxyConfig";
import { history, useLocation, useModel } from 'umi';
import {
  Alert,
  Button,
  Card,
  Checkbox,
  Col,
  DatePicker,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Row,
  Select,
  Space,
  TreeSelect,
  Upload,
} from 'antd';
import { CheckboxChangeEvent } from 'antd/es/checkbox';
import { useForm } from 'antd/es/form/Form';
import { UploadFile } from 'antd/lib/upload';
import C from 'crypto-js';
import Base64 from 'crypto-js/enc-base64';
import Utf8 from 'crypto-js/enc-utf8';
import 'moment/locale/zh-cn'
import moment from 'moment';
import './index.less'
import React, { useEffect, useState } from 'react';
import {LocalFormat} from "@/utils/localHelper";
import locale from "antd/es/date-picker/locale/zh_CN";
// import './index.less';
const Index: React.FC = (props) => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const location = useLocation();
  const [form] = useForm();
  //部门下拉框
  const [groupOptions, setGroupOptions] = useState([]);
  const [editObj, setEditObj] = useState({});
  const [myEditorHtml, setMyEditorHtml] = useState('');
  const [titleHtml, setTitleHtml] = useState('');
  const [myTitle, setMyTitle] = useState('');
  const [subTitle, setSubTitle] = useState('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [fjList, setFjList] = useState<UploadFile[]>([]);
  const [editorFileList, setEditorFileList] = useState<any[]>([]);
  const [isShow, setIsShow] = useState<boolean>(false);
  //文章预览弹框
  const [isWzShow, setIsWzShow] = useState<boolean>(false);
  //tree
  const [treeData, setTreeData] = useState([]);
  //select
  const [selectedTreeData, setSelectedTreeData] = useState([]);

  //定时
  const [checkDs, setCheckDs] = useState<boolean>(false);
  //多点
  const [checkDd, setCheckDd] = useState<boolean>(false);
  //封面新闻
  const [checkFmxw, setCheckFmxw] = useState<boolean>(false);

  //黑名单Modal
  const [isBlackListShow, setIsBlackListShow] = useState<boolean>(false);
  //黑名单List
  const [blackList, setBlackList] = useState<any>([]);

  //白名单Modal
  const [isWhiteListShow, setIsWhiteListShow] = useState<boolean>(false);
  //白名单List
  const [whiteList, setWhiteList] = useState<any>([]);

  //限制
  const [limitType, setLimitType] = useState<number>(0);
  const [ipList, setIpList] = useState('');
  const [hidTitle, setHidTitle] = useState(false);
  //更改树结构
  const changeTreeData = (data) => {
    for (let i = 0; i < data.length; i++) {
      const element = data[i];
      element.value = element.id;
      element.title = element.name;
      if (element.children && element.children.length > 0) {
        changeTreeData(element.children);
      }
    }
    return data;
  };

  //查询分类
  const getCategory = () => {
    const params = {
      type: 'topic',
      roleId:currentUser.roleId,
      filterType:'sub'
    };
    console.log(params,'params');
    //获取组list
    getCategoryList(params).then(async (res) => {
      const data = changeTreeData(res.data);
      console.log(data);
      setTreeData(data);
    });
  };
  const [pTime,setTime] = useState('')
  useEffect(() => {
    //获取组list
    form.setFieldsValue({hidTitle: false})
    getGroupList().then(async (res) => {
      if ((res.code = '0')) {
        const groupList = res.data.map((i) => {
          return { value: i.orgId, label: i.groupName };
        });
        setGroupOptions([...groupList]);
      } else {
        message.error(res.message);
      }
      getCategory();

      if (location.state) {
        const obj = location.state?.formValues;
        setEditObj(obj);
        setMyTitle(obj.title);
        setSubTitle(obj.subTitle);
        topicSelectOne({ id: obj.id }).then((res) => {
          if (res.code == '0') {
            setLimitType(res.data.limitType);
            setHidTitle(res.data.hidTitle || false);
            form.setFieldsValue({hidTitle: res.data.hidTitle || false})
            if (!res.data.fbrmc) {
              res.data.fbrmc = currentUser.name;
            }
            if(res.data.publishtime){
              setTime(res.data.publishtime)
            }
            if (!res.data.fbbm) {
              res.data.fbbm = currentUser.orgId;
            }
            if (res.data.sfds == 1) {
              if (!!res.data.publishtime) {
                res.data.publishtime = moment(res.data.publishtime);
              } else {
                res.data.publishtime = '';
              }
              setCheckDs(true);
            } else {
              res.data.publishtime = '';
            }
            if(res.data.ipList){
              form.setFieldValue('ipList',res.data.ipList)
              setIpList(res.data.ipList)
            }

            if (res.data.multipoint) {
              const arr = res.data.multipoint.split(',');
              setSelectedTreeData(arr);
              setCheckDd(true);
            }
            setIpList(res.data.ipList)
            setCheckFmxw(res.data.isCover && res.data.isCover == 1 ? true : false);
            // res.data.fbbm = parseInt(res.data.fbbm);
            // const base64 = C.enc.Base64.parse(res.data.richtext);
            // const words = C.enc.Utf8.stringify(base64);
            setTitleHtml(res.data.richtitle);
            setTimeout(()=>{
              setMyEditorHtml(res.data.richtext);
            },100)
            let list = [];
            let annexList = [];
            if (res.data.files && res.data.files.length > 0) {
              for (let i = 0; i < res.data.files.length; i++) {
                const element = res.data.files[i];
                if (element.kind == 'pic') {
                  list.push({
                    uid: element.id,
                    size: element.wjdx,
                    name: element.wjmc + '.' + element.wjgs,
                    fileName: element.wjmc + '.' + element.wjgs,
                    url: element.httpurl,
                    percent: 100,
                    response: { data: [element] },
                  });
                } else if (element.kind == 'annex') {
                  annexList.push({
                    uid: element.id,
                    size: element.wjdx,
                    name: element.wjmc + '.' + element.wjgs,
                    fileName: element.wjmc + '.' + element.wjgs,
                    url: element.httpurl,
                    percent: 100,
                    response: { data: [element] },
                  });
                }
              }
              res.data.uploadImgs = list;
              setFjList(annexList);
            }

            setFileList(list);
            setMyEditorHtml(res.data.richtext);
            form.setFieldsValue(res.data);
          }
        });
      }
    });
  }, []);
  const preview = ()=>{
    let files = [];
    const values = form.getFieldsValue()
    if(values.publishtime && typeof values.publishtime != 'string'){
      const d = values.publishtime._d
      values.publishtime = d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds()
    }

    values.limitType = limitType;
    if (checkDd) {
      if (Array.isArray(selectedTreeData)) {
        let strs = '';
        for (let i = 0; i < selectedTreeData.length; i++) {
          const element = selectedTreeData[i];
          strs = strs + element + ',';
        }
        const newStrs = strs.slice(0, -1);
        values.multipoint = newStrs;
      } else {
        values.multipoint = selectedTreeData;
      }
    }
    if (checkDs) {
      values.sfds = 1;
    } else {
      values.sfds = 0;
    }
    if (checkFmxw) {
      values.isCover = 1;
    } else {
      values.isCover = 0;
    }

    delete values.uploadImgs;

    //fileList img
    if (fileList.length > 0) {
      for (let i = 0; i < fileList.length; i++) {
        const element = fileList[i].response.data[0];
        if (element.id) {
          files.push(element);
        } else {
          files.push({
            id: element.fileId,
            kind: 'pic',
            localurl: element.url,
            origin: 'topic',
            pxh: 10,
            wjdx: element.fileSize,
            wjgs: element.fileType,
            wjmc: element.fileName,
          });
        }
      }
    }
    if(values.hideTitle && !titleHtml){
      message.error('请填写富文本标题!');
      return
    }
    values.richtitle = titleHtml
    //upload
    if (fjList && fjList.length > 0) {
      for (let j = 0; j < fjList.length; j++) {
        if (fjList[j].response.data.length > 0) {
          const element = fjList[j].response.data[0];
          if (element.id) {
            files.push(element);
          } else {
            files.push({
              id: element.fileId,
              kind: 'annex',
              localurl: element.url,
              origin: 'topic',
              pxh: 10,
              wjdx: element.fileSize,
              wjgs: element.fileType,
              wjmc: element.fileName,
            });
          }
        }
      }
    }

    //richtext
    if (editorFileList.length > 0) {
      files = [...files, ...editorFileList];
    }
    // values.fbbmmc += '';
    values.files = files;
    values.richtext = Base64.stringify(Utf8.parse(myEditorHtml));
    console.log(values);
    cacheTopic(values)
      .then((res) => {
        if (res.code == '0') {
          const url = HOMEPAGE_URL+'pages/article/preview.html?id='+res.data.topicId+'&type=preview'
          window.open(url)
        }
      })
      .catch(({ response }) => {
        message.error(response.data.data);
      });
    return

  }
  const onSubmit = async (values: any) => {
    console.log('onsubmit');
    console.log(values);

    let files = [];
    values.limitType = limitType;
    if (checkDd) {
      if (Array.isArray(selectedTreeData)) {
        let strs = '';
        for (let i = 0; i < selectedTreeData.length; i++) {
          const element = selectedTreeData[i];
          strs = strs + element + ',';
        }
        const newStrs = strs.slice(0, -1);
        values.multipoint = newStrs;
      } else {
        values.multipoint = selectedTreeData;
      }
    }
    if (checkDs) {
      values.sfds = 1;
    } else {
      values.sfds = 0;
    }
    if (checkFmxw) {
      values.isCover = 1;
    } else {
      values.isCover = 0;
    }
    delete values.uploadImgs;

    //fileList img
    if (fileList.length > 0) {
      for (let i = 0; i < fileList.length; i++) {
        const element = fileList[i].response.data[0];
        if (element.id) {
          files.push(element);
        } else {
          files.push({
            id: element.fileId,
            kind: 'pic',
            localurl: element.url,
            origin: 'topic',
            pxh: 10,
            wjdx: element.fileSize,
            wjgs: element.fileType,
            wjmc: element.fileName,
          });
        }
      }
    }

    //upload
    if (fjList && fjList.length > 0) {
      for (let j = 0; j < fjList.length; j++) {
        if (fjList[j].response.data.length > 0) {
          const element = fjList[j].response.data[0];
          if (element.id) {
            files.push(element);
          } else {
            files.push({
              id: element.fileId,
              kind: 'annex',
              localurl: element.url,
              origin: 'topic',
              pxh: 10,
              wjdx: element.fileSize,
              wjgs: element.fileType,
              wjmc: element.fileName,
            });
          }
        }
      }
    }

    //richtext
    if (editorFileList.length > 0) {
      files = [...files, ...editorFileList];
    }
    // values.fbbmmc += '';
    values.files = files;
    values.richtext = Base64.stringify(Utf8.parse(myEditorHtml));
    if(values.hideTitle && !titleHtml){
      message.error('请填写富文本标题!');
      return
    }
    values.richtitle = titleHtml
    if (location.state) {
      const obj = location.state?.formValues;
      values.id = obj.id;
      updateTopic(values)
        .then((res) => {
          if (res.code == '0') {
            message.success('保存成功！');
            history.push('/consultCenter/siteSearch');
          }
        })
        .catch(({ response }) => {
          message.error(response.data.data);
        });
    } else {
      insertTopic(values).then((res) => {
        if (res.code == '0') {
          message.success('保存成功！');
          history.push('/consultCenter/siteSearch');
        }
      });
    }
  };

  //定时
  const onChangeDs = (e: CheckboxChangeEvent) => {
    setCheckDs(e.target.checked);
  };

  //多点
  const onChangeDd = (e: CheckboxChangeEvent) => {
    setCheckDd(e.target.checked);
  };

  //封面新闻
  const onChangeFmxw = (e: CheckboxChangeEvent) => {
    setCheckFmxw(e.target.checked);
  };
  const normFile = (e: any, fileList) => {
    const isDuplicate = fjList.some(
      (item) =>
        item.name === e.file.name && item.response !== undefined && item.status != 'removed',
    );
    if (isDuplicate) {
      const filteredArr = fjList.filter((item) => item.response !== undefined);
      setFjList(filteredArr);
      return filteredArr;
    }

    if (Array.isArray(e)) {
      return e;
    }
    setFjList(e?.fileList);
    return e?.fileList;
  };
  const handleBeforeUpload = (file) => {
    const isDuplicate = fjList.some((item) => item.name === file.name);
    if (isDuplicate) {
      const filteredArr = fjList.filter((item) => item.response !== undefined);
      setFjList(filteredArr);
      message.error('不能重复上传文件');
      return false; // 阻止文件上传
    }

    // 允许文件上传
    return true;
  };

  return (
    <PageContainer
      header={{
        title: false,
      }}
    >
      <Card title="内容发布">
        <ProForm
          form={form}
          layout="horizontal"
          initialValues={{ fbrmc: currentUser?.name, fbbm: currentUser?.orgId }}
          // {...formLayout}
          submitter={{
            render: (_, dom) => (
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <Space>
                  {/*{dom}*/}
                  {<Button onClick={() => {
                    _.reset()
                  }}><UndoOutlined />重置</Button>}
                  {<Button type={"primary"} onClick={() => {
                    _.submit()
                  }}><CheckOutlined />提交</Button>}
                  {<Button onClick={() => {
                    preview()
                  }}><EyeOutlined />预览</Button>}
                </Space>
              </div>
            ),
          }}
          onFinish={onSubmit}
        >
          <Row gutter={[16, 16]}>
            <Col span={8}>
              <ProFormText
                rules={[
                  {
                    required: true,
                    message: '文章标题必填！',
                  },
                ]}
                onChange={(e) => setMyTitle(e.target.value)}
                width="md"
                name="title"
                placeholder="请输入文章标题"
                label="文章标题"
              />
            </Col>
            <Col span={8}>
              <ProFormText
                onChange={(e) => setSubTitle(e.target.value)}
                width="md"
                name="subTitle"
                placeholder="请输入副标题"
                label="副标题"
              />
            </Col>
            <Col span={8}>
              <ProFormText disabled={![1,5].includes(currentUser.authId)}  width="md" name="fbrmc" placeholder="请输入" label="发布作者" />
            </Col>
            <Col span={8}>
              <Form.Item
                label="发布部门"
                name="fbbm"
                width="md"
                rules={[
                  {
                    required: true,
                    message: '发布部门必填！',
                  },
                ]}
              >
                <Select className={'mySelect'} placeholder="请选择" options={groupOptions} allowClear />
              </Form.Item>
            </Col>
            <Col span={8}>

              <Form.Item
                label="富文本标题"
                name="hidTitle"
                width="md"
                rules={[
                  {
                    required: true,
                    message: '富文本标题必选！',
                  },
                ]}
              >
                <Radio.Group
                  defaultValue={hidTitle}
                  value={hidTitle}
                  onChange={(e) => setHidTitle(e.target.value)}
                >
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </Radio.Group>
              </Form.Item>

            </Col>

            <Col span={8}>
              <Form.Item
                label={<span>本站分类</span>}
                name="classify"
                width="md"
                rules={[
                  {
                    required: true,
                    message: '本站分类必填！',
                  },
                ]}
              >
                <TreeSelect className={'mySelect'} treeData={treeData} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <ProFormText
                width="md"
                name="origin"
                placeholder="请输入"
                label={<span style={{ marginLeft: 10 }}>信息来源</span>}
              />
            </Col>
            <Col span={8}>
              <ProFormText
                width="md"
                name="tag"
                placeholder="请输入"
                label={<span style={{ marginLeft: 10 }}>设置标签</span>}
              />
            </Col>

            <Col span={12}>
              <ProFormTextArea
                width="md"
                name="excerpt"
                placeholder="请输入"
                label={<span style={{ marginLeft: 10 }}>信息摘要</span>}
              />
            </Col>
            <Col span={12}></Col>

            <Col span={12}>
              <Checkbox onChange={onChangeFmxw} style={{ marginBottom: 10 }} checked={checkFmxw}>
                封面新闻
              </Checkbox>
              {checkFmxw ? (
                <Form.Item
                  label={<span style={{ marginLeft: 10 }}>封面图片</span>}
                  name="uploadImgs"
                  rules={[
                    {
                      required: true,
                      message: '封面图片必填！',
                    },
                  ]}
                >
                  <ImgUpload form={form} fileList={fileList} setFileList={setFileList} />
                </Form.Item>
              ) : null}
            </Col>
              {
                 hidTitle ?
                   <Row>
                     <Col span={2}>
                       富文本标题:
                     </Col>
                     <Col span={21} >
                       <MyTextEditor
                         style={{width:'900px'}}
                         myEditorHtml={titleHtml}
                         setMyEditorHtml={setTitleHtml}
                         type={'text'}
                       />
                     </Col>
                   </Row>
                 : null
              }
            <Row>
              <Col span={2}>
                文章内容:
              </Col>
              <Col span={21}>
                <MyEditor
                  style={{width:'900px'}}
                  myEditorHtml={myEditorHtml}
                  setMyEditorHtml={setMyEditorHtml}
                  editorFileList={editorFileList}
                  setEditorFileList={setEditorFileList}
                />
              </Col>
            </Row>
{/*            <Col span={20} style={{ marginLeft: 80 }}>
              <MyEditor
                myEditorHtml={myEditorHtml}
                setMyEditorHtml={setMyEditorHtml}
                editorFileList={editorFileList}
                setEditorFileList={setEditorFileList}
              />
            </Col>*/}
            <Col span={24}>
              <div className="ant-card-head" style={{ padding: 0 }}>
                <div className="ant-card-head-wrapper">
                  <div className="ant-card-head-title">高级配置</div>
                </div>
              </div>
            </Col>

            <Col span={12}>
              <Form.Item
                label={
                  <Checkbox onChange={onChangeDs} checked={checkDs}>
                    发布时间
                  </Checkbox>
                }
                name="publishtime"
              >
                <DatePicker
                  locale={locale}
                  showTime={{ format: 'HH:mm:ss' }}
                  format="YYYY-MM-DD HH:mm:ss"
                  disabled={!checkDs}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="限制状态">
                <Radio.Group
                  defaultValue={limitType}
                  value={limitType}
                  onChange={(e) => setLimitType(e.target.value)}
                >
                  <Radio value={0}>空</Radio>
                  <Radio value={1}>白名单模式（用分号隔开）</Radio>
                  <Radio value={2}>黑名单模式（用分号隔开）</Radio>
                </Radio.Group>
                <Form.Item name="ipList">
                  {limitType !== 0 ? (
                    <div>
                      <Input.TextArea
                        key={limitType}
                        defaultValue={ipList}
                        style={{ width: '80%', marginTop: 5 }}
                        placeholder={limitType == 2 ? '请输入黑名单' : '请输入白名单'}
                      ></Input.TextArea>
                      <Alert
                        style={{ width: '80%', marginTop: 5 }}
                        message="多个IP地址用;分号分隔"
                        type="error"
                      />
                    </div>

                  ) : null}
                </Form.Item>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={
                  <Checkbox onChange={onChangeDd} checked={checkDd}>
                    多点发布
                  </Checkbox>
                }
              >
                <a onClick={() => (checkDd ? setIsShow(true) : null)}>选择类别</a>
              </Form.Item>
            </Col>
            <Col span={12}></Col>

            <Col span={12}>
              <Form.Item
                name="upload"
                label="插入附件"
                valuePropName="files"
                getValueFromEvent={normFile}
                extra="支持扩展名：.rar .zip .doc .docx .pdf .jpg..."
              >
                <Upload
                  name="file"
                  action="/api/v1/topic/batchUpload"
                  fileList={fjList}
                  // onChange={handleChange}
                  headers={{'Token':'Bearer ' + window.sessionStorage.getItem('userToken')}}
                  beforeUpload={handleBeforeUpload}
                >
                  <Button icon={<UploadOutlined />}>上传附件</Button>
                </Upload>
              </Form.Item>
            </Col>
            <Col span={12}/>
          </Row>
          <Row/>
        </ProForm>
        <Modal
          title="类别选择"
          open={isShow}
          onCancel={() => setIsShow(false)}
          onOk={() => setIsShow(false)}
        >
          <TreeSide
            defaultData={treeData}
            multiple={true}
            setSelectedTreeData={setSelectedTreeData}
            selectedTreeData={selectedTreeData}
          />
        </Modal>
        <Modal
          destroyOnClose
          title="文章预览"
          open={isWzShow}
          onCancel={() => setIsWzShow(false)}
          width={780}
          onOk={() => setIsWzShow(false)}
        >
          <ArticlePreview time={pTime} editHtml={myEditorHtml} title={myTitle} />
        </Modal>
        <IpListModal
          title={limitType == 2 ? '黑名单选择' : '白名单选择'}
          isIpShow={limitType == 2 ? isBlackListShow : isWhiteListShow}
          setIsIpShow={limitType == 2 ? setIsBlackListShow : setIsWhiteListShow}
          ipList={limitType == 2 ? blackList : whiteList}
          setIpList={limitType == 2 ? setBlackList : setWhiteList}
        />

        {/* <BlackListModal
          isBlackListShow={isBlackListShow}
          setIsBlackListShow={setIsBlackListShow}
          blackList={blackList}
          setBlackList={setBlackList}
        />
        <WhiteListModal
          isWhiteListShow={isWhiteListShow}
          setIsWhiteListShow={setIsWhiteListShow}
          whiteLists={whiteList}
          setWhiteList={setWhiteList}
        /> */}
      </Card>
    </PageContainer>
  );
};

export default Index;
